package com.dqp.cslggroup.Util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.Log;
import com.dqp.cslggroup.UI.MyApplication;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.dqp.cslggroup.Util.GetTimeUtil.day_for_year;

public class TimeTools {

    /**
     * 计算当前周数
     */
    public static int course_zhoushu(Context context) {
        int[] Time_data;
        int zhoushu = 0;
        String xl = SharedPreferencesUtil.getStringSp(context, "Start_date", null);
        if (!StringUtil.isEmpty(xl, 5)) {
            Log.e("xl", xl);
            String today = GetTimeUtil.getNowDate();
            int count = GetTimeUtil.addDates(xl, today);
            if (count < 7) {
                zhoushu = 1;
            } else if (count % 7 != 0) {
                zhoushu = count / 7 + 1;
            } else zhoushu = count / 7;
            return zhoushu;
        }

        if (StringUtil.isEmpty(xl, 5)) {
            List<com.dqp.cslggroup.bean.Calendar> calendars = MyApplication.getDaoInstant().getCalendarDao().loadAll();
            if (calendars.size() > 0) {
                com.dqp.cslggroup.bean.Calendar calendar = calendars.get(0);
                if (StringUtil.isEmpty(calendar.getTeachWeek(), 5)) return Integer.parseInt(calendar.getTeachWeek());
            }
        }

        if (StringUtil.isEmpty(xl, 5)) {
            xl = SharedPreferencesUtil.getStringSp(context, "xl", null);
            if (xl != null && xl.contains("学年")) {
                Time_data = StringUtil.SelectNumber(StringUtil.RemoveBrackets(xl));
                int now_day = GetTimeUtil.getDay();
                int now_month = GetTimeUtil.getMonth();
                int now_year = GetTimeUtil.getYear();
                int start_day = Time_data[2];
                int start_mouth = Time_data[1];
                int start_year = Time_data[0];
                int end_year = Time_data[3];
                int end_mouth = Time_data[4];
                int end_day = Time_data[5];
                int now_days, year_days, start_days, end_days;
                start_days = day_for_year(start_year, start_mouth, start_day);
                now_days = day_for_year(now_year, now_month, now_day);
                end_days = day_for_year(end_year, end_mouth, end_day);
                if (now_year % 4 == 0 && now_year % 100 != 0 || now_year % 400 == 0) {
                    year_days = 365;
                } else {
                    year_days = 365;
                }
                if (now_year == start_year && now_days >= start_days) {
                    zhoushu = 1 + (now_days - start_days) / 7;
                }
                if (now_days < end_days && now_year == end_year && now_month < 2) {
                    zhoushu = (year_days - start_days + now_days) / 7 + 1;
                }
            }
        }
        return zhoushu;
    }


    /**
     * 计算2个时间之差，返回天数(实际的情况是还书时间减去现在时间)
     */
    public static String getday(String secourd) {
        try {
            @SuppressLint("SimpleDateFormat") DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date date_return = df.parse(secourd);
            @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date curDate = new Date(System.currentTimeMillis());
            String str = formatter.format(curDate);
            Date date_now = df.parse(str);
            long diff = date_return.getTime() - date_now.getTime();// 这样得到的差值是微秒级别
            long days = diff / (1000 * 60 * 60 * 24);
            return days + "";
        } catch (Exception e) {
            return null;
        }
    }

    // 将日期转化为对应的星期几
    public static String xinqi() {
        Date dates = new Date();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String week = dateFormat.format(dates);
        final String[] dayNames = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        try {
            date = sdfInput.parse(week);
        } catch (Exception e) {
            e.printStackTrace();
        }
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek < 0)
            dayOfWeek = 0;
        return dayNames[dayOfWeek];
    }

    // 将日期转化为对应的星期几
    public static String toxinqi(int x) {
        final String[] dayNames = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        return dayNames[x];
    }

    // 将日期转化为对应的星期
    public static int week() {
        Date dates = new Date();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String week = dateFormat.format(dates);
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        try {
            date = sdfInput.parse(week);
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert date != null;
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek < 0)
            dayOfWeek = 0;
        if (dayOfWeek == 0)
            dayOfWeek = 6;
        else dayOfWeek -= 1;
        return dayOfWeek;
    }

    /**
     * 判断当前系统时间是否在特定时间的段内
     *
     * @param beginHour 开始的小时，例如5
     * @param beginMin  开始小时的分钟数，例如00
     * @param endHour   结束小时，例如 8
     * @param endMin    结束小时的分钟数，例如00
     * @return true表示在范围内，否则false
     */
    public static boolean isCurrentInTimeScope(int beginHour, int beginMin, int endHour, int endMin) {
        boolean result = false;// 结果
        final long aDayInMillis = 1000 * 60 * 60 * 24;// 一天的全部毫秒数
        final long currentTimeMillis = System.currentTimeMillis();// 当前时间

        Time now = new Time();// 注意这里导入的时候选择android.text.format.Time类,而不是java.sql.Time类
        now.set(currentTimeMillis);

        Time startTime = new Time();
        startTime.set(currentTimeMillis);
        startTime.hour = beginHour;
        startTime.minute = beginMin;

        Time endTime = new Time();
        endTime.set(currentTimeMillis);
        endTime.hour = endHour;
        endTime.minute = endMin;

        if (!startTime.before(endTime)) {
            // 跨天的特殊情况（比如22:00-8:00）
            startTime.set(startTime.toMillis(true) - aDayInMillis);
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
            Time startTimeInThisDay = new Time();
            startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis);
            if (!now.before(startTimeInThisDay)) {
                result = true;
            }
        } else {
            // 普通情况(比如 8:00 - 14:00)
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
        }
        return result;
    }

    /**
     * 得到几天前的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    public static int getDateBeforeYear(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.get(Calendar.YEAR);
    }

    public static int getDateBeforeMonth(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.get(Calendar.MONTH);
    }

    public static int getDateBeforeDay(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.get(Calendar.DATE);
    }

    /**
     * 得到几天后的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateAfter(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }

    public static int getDateAfterYear(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.get(Calendar.YEAR);
    }

    public static int getDateAfterMonth(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.get(Calendar.MONTH);
    }

    public static int getDateAfterDay(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.get(Calendar.DATE);
    }


}
